package org.chen.config;

import lombok.extern.slf4j.Slf4j;
import org.chen.dto.RateLimiterConfigDTO;
import org.chen.model.CommentFieldPattern;
import org.chen.model.RateLimiterConfig;
import org.chen.service.DistributedRateLimiter;
import org.chen.service.impl.CommentFieldPatternServiceImpl;
import org.chen.service.impl.RateLimiterConfigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static org.chen.service.impl.CommentFieldPatternServiceImpl.DEFAULT_PATTERNS;

@Configuration
@Slf4j
public class PatternsInit {

    @Autowired
    private CommentFieldPatternServiceImpl commentFieldPatternService;

    @Autowired
    private RateLimiterConfigServiceImpl rateLimiterConfigService;

    @Autowired
    private DistributedRateLimiter config;

    /**
     * 系统启动时初始化默认规则
     */
    @PostConstruct
    public void initDefaultPatterns() {
        try {
            long count = commentFieldPatternService.count();
            // 检查数据库是否为空
            if (count == 0) {
                log.info("正在初始化默认匹配规则...");
                List<CommentFieldPattern> defaultPatterns = new ArrayList<>();
                LocalDateTime now = LocalDateTime.now();

                // 将默认规则转换为实体对象
                DEFAULT_PATTERNS.forEach((fieldType, patterns) -> {
                    patterns.forEach(pattern -> {
                        CommentFieldPattern entity = new CommentFieldPattern();
                        entity.setFieldType(fieldType.name());
                        entity.setPattern(pattern);
                        entity.setDescription("默认规则");
                        entity.setIsEnabled(true);
                        entity.setCreateTime(now);
                        entity.setUpdateTime(now);
                        defaultPatterns.add(entity);
                    });
                });

                // 批量保存到数据库
                commentFieldPatternService.saveBatch(defaultPatterns);
                log.info("默认匹配规则初始化完成，共{}条规则", defaultPatterns.size());

                // 刷新缓存
                commentFieldPatternService.refreshAllCache();
            }else {
                log.info("目前共{}条规则", count);
            }
        } catch (Exception e) {
            log.error("初始化默认匹配规则失败", e);
        }
    }

    @PostConstruct
    public void initConfig() {
        try {
            // 从数据库加载配置
            List<RateLimiterConfig> configs = rateLimiterConfigService.list();

            // 转换为DTO
            RateLimiterConfigDTO configDTO = new RateLimiterConfigDTO();
            for (RateLimiterConfig config : configs) {
                switch (config.getConfigKey()) {
                    case "max_concurrent_per_domain" -> configDTO.setMaxConcurrentPerDomain(config.getConfigValue());
                    case "global_concurrent" -> configDTO.setGlobalConcurrent(config.getConfigValue());
                    case "min_interval" -> configDTO.setMinInterval(config.getConfigValue());
                    case "max_interval" -> configDTO.setMaxInterval(config.getConfigValue());
                    case "domain_interval" -> configDTO.setDomainInterval(config.getConfigValue());
                }
            }

            // 保存到Redis
            rateLimiterConfigService.saveToRedis(configDTO);

            config.updateConfig(configDTO);
        } catch (Exception e) {
            log.error("初始化限流配置失败", e);
        }
    }
}
